<?php

/*
 * litchicms
 * Copyright (C) 2010-5-1 Author: tiefa(539247@qq.com)
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
!defined('BRK') && exit("!");


/**
 * addslashes数组和字符串
 * @param  $string or $array
 * @return $string or $array
 */
$KEYOUT = array('\'' => '_', '"' => '_', ',' => '_', ' ' => '_', '\\' => '_',);

function brk_addslashes($value) {
    if (is_array($value)) {
        $str = implode("", array_keys($value));
        if (strtr($str, $GLOBALS['KEYOUT']) != $str) {
            header301("/");
        }
        $value = array_map('brk_addslashes', $value);
    } else {
        $value = addslashes(trim($value));
    }
    return $value;
}

/**
 * addslashes数组和字符串
 * @param  string or array $value
 * @return $string or $array
 */
function brk_stripslashes($value) {
    $value = is_array($value) ? array_map('brk_stripslashes', $value) : stripslashes($value);
    return $value;
}

/**
 * @name dump
 */
function dump($var, $echo=true) {
    ob_start();
    var_dump($var);
    $str = ob_get_clean();
    $str = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $str);
    $str = '<div style=\'margin:10px;border:1px solid #555; border-top:6px solid #555; border-bottom:3px solid #555;padding:10px;text-align:left\'><pre>' . htmlspecialchars($str, ENT_QUOTES) . '</pre></div><br/><br/><br/>';
    if ($echo) {
        echo $str;
    } else {
        return $str;
    }
}

/**
 * @name get_ip  获取IP
 * @return string
 */
function brk_get_ip() {
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $temp = array();
    preg_match("/[\d\.]{7,15}/", $ip, $temp);
    $ip = $temp[0] ? $temp[0] : '0.0.0.0';
    unset($temp);
    return $ip;
}

/**
 * @name get_browser 获取浏览器类型
 * @return $string
 */
function brk_get_browser2() {
    return $_SERVER['HTTP_USER_AGENT'];
}

/**
 * 检查文件夹,不存在创建
 * @param $dirname string
 */
function check_make_dir($dirname) {
    if (is_dir(dirname($dirname))) {
        !is_dir($dirname) && !mkdir($dirname, 0777) && exit('error!  mkdir --' . $dirname . ' -- base.fun.php');
    } else {
        check_make_dir(dirname($dirname));
        check_make_dir($dirname);
    }
}

/**
 * @name syslog
 * @note 记录日志
 */
function brk_log($typenumber = -1, $str = "") {
    if ($typenumber == -1)
        return;
    switch ($typenumber) {
        case 0:
            $type = "error";
            break;
        case 1:
            $type = 'tpl';
            break;
        case 6:
            $type = "mysql";
            break;
    }
    global $BRK_GLOBAL;



    check_make_dir($dir = SYSTEM . "log/" . $BRK_GLOBAL['datearray']['year'] . "/" . $BRK_GLOBAL['datearray']['mon']);
    if (!is_file($file = $dir . '/' . $BRK_GLOBAL['datearray']['mday'] . ".php")) {
        $handle = fopen($file, "a");
        if (fwrite($handle, "<?php exit; ?>\n") === FALSE)
            exit('fwrite --' . $file . ' -- base.fun.php'); // "不能写入到文件 $file";

























    }else {
        $handle = fopen($file, "a");
    }
    $logstr = '['
            . $BRK_GLOBAL['datearray']['year'] . '-' . $BRK_GLOBAL['datearray']['mon'] . '-' . $BRK_GLOBAL['datearray']['mday'] . ' '
            . $BRK_GLOBAL['datearray']['hours'] . ':' . $BRK_GLOBAL['datearray']['minutes'] . ':' . $BRK_GLOBAL['datearray']['seconds']
            . '][' . $type . ']' . ( is_array($str) ? implode("\n ", $str) : "\n" . $str );
    if (fwrite($handle, $logstr . "\n\n") === FALSE)
        exit('fwrite --' . $file . ' -- base.fun.php'); // "不能写入到文件 $file";
 fclose($handle);
    if ($typenumber == 0) {
        ob_header_char();
        if (TRUE === DEBUG) {
            echo $logstr . "<br/>";
        }
        exit("System error, check log file.");
    }
//今后实现 | 限制日志文件大小  如果日志文件超过大小限制:分卷
}

/*
 * @name header301
 * @note 页面永久重定向
 */

function header301($url) {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: " . $GLOBALS['BRK_CONF']['rootdir'] . $url);
    exit();
}

/*
 * @name headerLocation
 * @note header跳转
 */

function headerLocation($url) {
    header("Location: $url");
    exit();
}

/**
 * @name ob_header
 * @note 开启缓冲区,并且发送一个header("Content-type: text/html; charset=utf-8");
 */
function ob_header_char($char='utf-8') {
    ob_start();
    header("Content-type: text/html; charset=$char");
}

/**
 * get_lang
 * @param string $key 键名
 * @param string $args 参数
 * @return string 按照缓存模式格式化后的URL组成部分
 */
function get_lang($key, $args=NULL) {
    global $BRK_LANG;
    if ($args == NULL) {
        return $BRK_LANG[$key];
    }
    if (is_string($args)) {
        return str_replace('$', $args, $BRK_LANG[$key]);
    }
    if (is_array($args)) {
        return preg_replace(array_fill(0, count($args), '/\$/'), $args, $BRK_LANG[$key], 1);
    }
}

/**
 * check_rights_by_id
 * @param int $right
 * @return bool 如果存在该权限....
 */
function check_rights_by_id($right, $autoexit=TRUE) {
    if (key_exists("RIGTHS", $GLOBALS['BRK_GLOBAL']) && key_exists($right, $GLOBALS['BRK_GLOBAL']['RIGTHS']['node'])) {
        return TRUE;
    } else {
        if ($autoexit) {
            msg('您没有足够的权限执行此操作!');
        }
        return FALSE;
    }
}

/**
 * 提示消息
 * @param $message 消息
 * @param $title 页面标题
 * @param $link 跳转地址
 * @param $auto 是否自动跳转
 */
function msg($message, $title="message", $link="index.php", $auto=FALSE) {
    $GLOBALS['ismsg'] = TRUE;
    ob_clean();
    if (is_array($message)) {
        $MESSAGE = $message[0];
        if (in_array('t', $message)) {
            global $BRK_GLOBAL;
            if (!empty($BRK_GLOBAL['tempfile'])) {
                $MESSAGE.="tplfile:" . $BRK_GLOBAL['tempfile'] . ".php";
            }
        }
        //
        //if(){
        //}
        //
    } else {
        $MESSAGE = $message;
    }

    $TITLE = $title;
    $LINK = $link;
    $AUTO = $auto;

    !function_exists('template') && require 'template.fun.php';
    include template('msg.php');
    exit;
}

/**
 * 构造合适任意目录的URL (独立域名或者1域名下的目录)
 */
function buildUrl($str=FALSE) {
    if (is_string($str)) {
        if ($str{0} !== '/') {
            $str = '/' . $str;
        }
    } else {
        $str = '/';
    }
    return $GLOBALS['BRK_CONF']['rootdir'] . $str;
}

/**
 * 引入权限
 */
function require_rigths() {
    global $BRK_USER, $BRK_GLOBAL;
    $temp = empty($BRK_USER) ? 1 : ($BRK_USER['group_id'] ? $BRK_USER['group_id'] : 1);
    if (is_file($temp = SYSTEM . 'data/group_rigths/' . $temp . '.php')) {
        $BRK_GLOBAL['RIGTHS'] = require $temp;
    } else {
        ob_header_char("utf-8");
        exit("权限文件不存在,无法继续程序");
    }
}